# -*- coding: utf-8 -*-
"""
主窗口界面
现代化的时间计算器主界面
"""

from PyQt5.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                            QTabWidget, QLabel, QFrame, QPushButton, QApplication,
                            QStatusBar, QMenuBar, QAction, QMessageBox)
from PyQt5.QtCore import Qt, QTimer, QSize
from PyQt5.QtGui import QFont, QIcon, QPalette, QColor

import sys
import os

# 添加模块搜索路径
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)

# 导入子模块
try:
    from .widgets.date_calculator_tab import DateCalculatorTab
    from .widgets.time_calculator_tab import TimeCalculatorTab
    from .widgets.special_functions_tab import SpecialFunctionsTab
    from .widgets.history_tab import HistoryTab
except ImportError:
    # 如果相对导入失败，尝试绝对导入
    from widgets.date_calculator_tab import DateCalculatorTab
    from widgets.time_calculator_tab import TimeCalculatorTab
    from widgets.special_functions_tab import SpecialFunctionsTab
    from widgets.history_tab import HistoryTab

# 导入工具模块
try:
    from utils.history_manager import HistoryManager
except ImportError:
    import importlib.util
    utils_path = os.path.join(parent_dir, "utils", "history_manager.py")
    if os.path.exists(utils_path):
        spec = importlib.util.spec_from_file_location("history_manager", utils_path)
        history_module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(history_module)
        HistoryManager = history_module.HistoryManager
    else:
        raise ImportError("无法找到 history_manager 模块")


class MainWindow(QMainWindow):
    """主窗口类"""
    
    def __init__(self):
        super().__init__()
        # 创建共享的历史管理器
        self.history_manager = HistoryManager()
        self.init_ui()
        self.setup_menu()
        self.setup_status_bar()
        self.setup_timer()
        self.apply_styles()
    
    def init_ui(self):
        """初始化用户界面"""
        # 设置窗口基本属性
        self.setWindowTitle("时间计算器 v1.0 - 现代化桌面应用")
        self.setMinimumSize(1200, 850)
        self.resize(1300, 900)
        
        # 居中显示
        self.center_window()
        
        # 创建中央控件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(15)
        
        # 创建标题区域
        title_frame = self.create_title_frame()
        main_layout.addWidget(title_frame)
        
        # 创建标签页控件
        self.tab_widget = QTabWidget()
        self.tab_widget.setTabPosition(QTabWidget.North)
        self.tab_widget.setMovable(False)
        self.tab_widget.setUsesScrollButtons(True)
        self.tab_widget.setMinimumHeight(600)
        
        # 添加各个功能标签页
        self.setup_tabs()
        
        main_layout.addWidget(self.tab_widget)
    
    def create_title_frame(self):
        """创建标题区域"""
        title_frame = QFrame()
        title_frame.setMinimumHeight(120)
        title_frame.setMaximumHeight(120)
        title_frame.setFrameStyle(QFrame.NoFrame)
        title_frame.setStyleSheet("""
            QFrame {
                background-color: #ffffff;
                border: 2px solid #e9ecef;
                border-radius: 10px;
            }
        """)
        
        layout = QHBoxLayout(title_frame)
        layout.setContentsMargins(30, 20, 30, 20)
        layout.setSpacing(30)
        
        # 左侧标题区域
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        left_layout.setContentsMargins(0, 0, 0, 0)
        left_layout.setSpacing(8)
        
        # 应用图标和标题
        title_label = QLabel("⏰ 时间计算器")
        title_font = QFont("Microsoft YaHei", 22, QFont.Bold)
        title_label.setFont(title_font)
        title_label.setStyleSheet("""
            QLabel {
                color: #2c3e50;
                background: transparent;
                border: none;
                padding: 0px;
                margin: 0px;
            }
        """)
        title_label.setMinimumHeight(35)
        
        # 副标题
        subtitle_label = QLabel("专业的日期时间计算工具")
        subtitle_font = QFont("Microsoft YaHei", 12)
        subtitle_label.setFont(subtitle_font)
        subtitle_label.setStyleSheet("""
            QLabel {
                color: #7f8c8d;
                background: transparent;
                border: none;
                padding: 0px;
                margin: 0px;
            }
        """)
        subtitle_label.setMinimumHeight(25)
        
        left_layout.addWidget(title_label)
        left_layout.addWidget(subtitle_label)
        left_layout.addStretch()
        
        # 右侧当前时间显示
        self.current_time_label = QLabel()
        self.current_time_label.setFont(QFont("Microsoft YaHei", 11))
        self.current_time_label.setMinimumWidth(220)
        self.current_time_label.setMinimumHeight(70)
        self.current_time_label.setMaximumHeight(70)
        self.current_time_label.setStyleSheet("""
            QLabel {
                color: #495057;
                background-color: #f8f9fa;
                border: 2px solid #dee2e6;
                border-radius: 8px;
                padding: 10px;
            }
        """)
        self.current_time_label.setAlignment(Qt.AlignCenter)
        
        layout.addWidget(left_widget)
        layout.addStretch()
        layout.addWidget(self.current_time_label)
        
        return title_frame
    
    def setup_tabs(self):
        """设置标签页"""
        # 日期计算标签页
        self.date_calc_tab = DateCalculatorTab(self.history_manager)
        self.tab_widget.addTab(self.date_calc_tab, "📅 日期计算")
        
        # 时间计算标签页
        self.time_calc_tab = TimeCalculatorTab(self.history_manager)
        self.tab_widget.addTab(self.time_calc_tab, "⏰ 时间计算")
        
        # 特殊功能标签页
        self.special_tab = SpecialFunctionsTab(self.history_manager)
        self.tab_widget.addTab(self.special_tab, "🎊 特殊功能")
        
        # 历史记录标签页
        self.history_tab = HistoryTab(self.history_manager)
        self.tab_widget.addTab(self.history_tab, "📊 历史记录")
        
        # 设置默认选中第一个标签页
        self.tab_widget.setCurrentIndex(0)
    
    def setup_menu(self):
        """设置菜单栏"""
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu('文件(&F)')
        
        new_action = QAction('新建计算(&N)', self)
        new_action.setShortcut('Ctrl+N')
        new_action.triggered.connect(self.new_calculation)
        file_menu.addAction(new_action)
        
        file_menu.addSeparator()
        
        exit_action = QAction('退出(&X)', self)
        exit_action.setShortcut('Alt+F4')
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 编辑菜单
        edit_menu = menubar.addMenu('编辑(&E)')
        
        copy_action = QAction('复制结果(&C)', self)
        copy_action.setShortcut('Ctrl+C')
        copy_action.triggered.connect(self.copy_result)
        edit_menu.addAction(copy_action)
        
        clear_action = QAction('清空(&L)', self)
        clear_action.setShortcut('Ctrl+L')
        clear_action.triggered.connect(self.clear_all)
        edit_menu.addAction(clear_action)
        
        # 视图菜单
        view_menu = menubar.addMenu('视图(&V)')
        
        refresh_action = QAction('刷新(&R)', self)
        refresh_action.setShortcut('F5')
        refresh_action.triggered.connect(self.refresh_current_tab)
        view_menu.addAction(refresh_action)
        
        # 帮助菜单
        help_menu = menubar.addMenu('帮助(&H)')
        
        about_action = QAction('关于(&A)', self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
    
    def setup_status_bar(self):
        """设置状态栏"""
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        
        # 显示就绪状态
        self.status_bar.showMessage("就绪", 3000)
        
        # 添加永久显示的信息
        version_label = QLabel("v1.0")
        version_label.setStyleSheet("color: #7f8c8d; margin-right: 10px;")
        self.status_bar.addPermanentWidget(version_label)
    
    def setup_timer(self):
        """设置定时器用于更新当前时间"""
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_current_time)
        self.timer.start(1000)  # 每秒更新一次
        self.update_current_time()  # 立即更新一次
    
    def update_current_time(self):
        """更新当前时间显示"""
        import pendulum
        now = pendulum.now('Asia/Shanghai')
        time_text = now.format('YYYY年MM月DD日 HH:mm:ss dddd')
        self.current_time_label.setText(f"当前时间\n{time_text}")
    
    def center_window(self):
        """将窗口居中显示"""
        screen = QApplication.desktop().screenGeometry()
        window = self.geometry()
        x = (screen.width() - window.width()) // 2
        y = (screen.height() - window.height()) // 2
        self.move(x, y)
    
    def apply_styles(self):
        """应用样式表"""
        style = """
        QMainWindow {
            background-color: #f8f9fa;
        }
        
        QTabWidget::pane {
            border: 1px solid #ddd;
            background-color: white;
            border-radius: 5px;
        }
        
        QTabWidget::tab-bar {
            left: 5px;
        }
        
        QTabBar::tab {
            background-color: #e9ecef;
            border: 1px solid #ddd;
            padding: 8px 16px;
            margin-right: 2px;
            border-top-left-radius: 5px;
            border-top-right-radius: 5px;
            min-width: 100px;
        }
        
        QTabBar::tab:selected {
            background-color: white;
            border-bottom-color: white;
            font-weight: bold;
        }
        
        QTabBar::tab:hover {
            background-color: #f1f3f4;
        }
        
        QFrame {
            background-color: white;
            border-radius: 8px;
        }
        
        QMenuBar {
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }
        
        QMenuBar::item {
            padding: 4px 8px;
            background-color: transparent;
        }
        
        QMenuBar::item:selected {
            background-color: #e9ecef;
            border-radius: 3px;
        }
        
        QStatusBar {
            background-color: #f8f9fa;
            border-top: 1px solid #dee2e6;
        }
        """
        self.setStyleSheet(style)
    
    def new_calculation(self):
        """新建计算"""
        current_tab = self.tab_widget.currentWidget()
        if hasattr(current_tab, 'clear_inputs'):
            current_tab.clear_inputs()
        self.status_bar.showMessage("已清空当前计算", 2000)
    
    def copy_result(self):
        """复制结果到剪贴板"""
        current_tab = self.tab_widget.currentWidget()
        if hasattr(current_tab, 'copy_result'):
            current_tab.copy_result()
            self.status_bar.showMessage("结果已复制到剪贴板", 2000)
        else:
            self.status_bar.showMessage("当前页面没有可复制的结果", 2000)
    
    def clear_all(self):
        """清空所有输入"""
        current_tab = self.tab_widget.currentWidget()
        if hasattr(current_tab, 'clear_all'):
            current_tab.clear_all()
        self.status_bar.showMessage("已清空所有内容", 2000)
    
    def refresh_current_tab(self):
        """刷新当前标签页"""
        current_tab = self.tab_widget.currentWidget()
        if hasattr(current_tab, 'refresh_history'):
            current_tab.refresh_history()
        elif hasattr(current_tab, 'load_history_data'):
            current_tab.load_history_data()
        self.status_bar.showMessage("页面已刷新", 2000)
    
    def show_about(self):
        """显示关于对话框"""
        QMessageBox.about(self, "关于时间计算器", 
                         """
                         <h2>时间计算器 v1.0</h2>
                         <p>现代化的桌面时间计算工具</p>
                         <p><b>功能特色：</b></p>
                         <ul>
                         <li>日期加减计算</li>
                         <li>时间间隔计算</li>
                         <li>工作日计算</li>
                         <li>节假日识别</li>
                         <li>历史记录管理</li>
                         </ul>
                         <p><b>技术栈：</b> Python + PyQt5</p>
                         <p>© 2024 时间计算器开发团队</p>
                         """)
    
    def closeEvent(self, event):
        """窗口关闭事件"""
        # 可以在这里添加保存设置等操作
        event.accept()
